<template>
  <div class="form-container">
    <!-- 添加标题 -->
    <div class="header">添加教学楼/学院楼相关信息</div>
    <!-- 添加带下划线的文字 -->
    <p class="form-description">所有内容都不允许为空，最多可以上传6张图片</p>

    <BeforeCreate/>

    <el-form
        ref="teachingBuildingForm"
        :model="formData"
        :rules="rules"
        class="responsive-form"
        label-position="left"
        label-width="120px"
    >
      <!-- 教学楼或学院楼号 -->
      <el-form-item label="楼号" prop="buildingId">
        <el-select
            v-model="formData.buildingId"
            placeholder="请选择教学楼或学院楼"
        >
          <el-option
              v-for="option in buildingOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 房间号 -->
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
            v-model="formData.roomNumber"
            placeholder="请输入房间号(如101,202A)"
        ></el-input>
      </el-form-item>

      <!-- 内容标题 -->
      <el-form-item label="内容标题" prop="contentTitle">
        <el-input
            v-model="formData.contentTitle"
            placeholder="请输入内容标题"
        ></el-input>
      </el-form-item>

      <!-- 内容描述 -->
      <el-form-item label="内容描述" prop="contentDescription">
        <el-input
            v-model="formData.contentDescription"
            :rows="4"
            placeholder="请输入内容描述（这里可以写一下房间位置指引和教室的情况等等，如114号514在WC对面，教室部分桌椅维修中等等）
                    可以下拉输入框便于输入"
            type="textarea"
        ></el-input>
      </el-form-item>

      <!-- 内容图片 -->
      <el-form-item label="内容图片" prop="contentImage">
        <el-upload
            :action=uploadUrl
            :file-list="formData.contentImage"
            :limit="6"
            :on-exceed="handleUploadExceed"
            :on-remove="handleUploadRemove"
            :on-success="handleUploadSuccess"
            accept="image/*"
            class="upload-demo"
            list-type="picture-card"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入验证码"></el-input>
        <el-button @click="generateCaptcha">{{ captchaText }}</el-button>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {inject, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import axios from "axios";
import router from "@/router/index.ts";
import BeforeCreate from "@/views/NewCreate/BeforeCreate.vue";

const uploadUrl = inject("uploadUrl");
const formData = ref({
  buildingId: null,
  roomNumber: '',
  contentTitle: '',
  contentDescription: '',
  contentImage: [],
  buildingName: '',
  code: ''
});

// 下拉选择框的选项
const buildingOptions = ref([
  {value: 1, label: '1号楼-公共教学楼', name: '公共教学楼'},
  {value: 2, label: '2号楼-公共教学楼', name: '公共教学楼'},
  {value: 3, label: '3号楼-公共教学楼', name: '公共教学楼'},
  {value: 4, label: '4号楼-公共教学楼', name: '公共教学楼'},
  {value: 5, label: '5号楼-公共教学楼', name: '公共教学楼'},
  {value: 6, label: '6号楼-公共教学楼', name: '公共教学楼'},
  {value: 7, label: '7号楼-计算机科学与工程学院', name: '计算机科学与工程学院'},
  {value: 8, label: '8号楼-计算机科学与工程学院', name: '计算机科学与工程学院'},
  {value: 9, label: '9号楼-理学院', name: '理学院'},
  {value: 10, label: '10号楼-继续教育学院', name: '继续教育学院'},
  {value: 11, label: '11号楼-材料科学与工程学院', name: '材料科学与工程学院'},
  {value: 12, label: '12号楼-计算机学院', name: '计算机学院'},
  {value: 13, label: '13号楼-工程训练中心', name: '工程训练中心'},
  {value: 14, label: '14号楼-自动化学院', name: '自动化学院'},
  {value: 15, label: '15号楼-机械工程学院', name: '机械工程学院'},
  {value: 16, label: '16号楼-电子信息工程学院', name: '电子信息工程学院'},
  {value: 17, label: '17号楼-环境科学与安全工程学院', name: '环境科学与安全工程学院'},
  {value: 18, label: '18号楼-化学化工学院', name: '化学化工学院'},
  {value: 19, label: '19号楼-化学化工学院', name: '化学化工学院'},
  {value: 20, label: '20号楼-汉语言文化学院', name: '汉语言文化学院'},
  {value: 21, label: '21号楼-功能晶体研究院', name: '功能晶体研究院'},
  {value: 22, label: '22号楼-艺术学院', name: '艺术学院'},
  {value: 23, label: '23号楼-聋人工学院', name: '聋人工学院'},
  {value: 24, label: '24号楼-国际工商学院', name: '国际工商学院'},
  {value: 25, label: '25号楼-管理学院', name: '管理学院'},
  {value: 27, label: '27号楼-海运学院', name: '海运学院'},
  {value: 28, label: '28号楼-公共教学楼', name: '公共教学楼'}
]);

// 监听 buildingId 的变化
watch(() => formData.value.buildingId, (newVal) => {
  if (newVal) {
    const selectedBuilding = buildingOptions.value.find(option => option.value === newVal);
    if (selectedBuilding) {
      formData.value.buildingName = selectedBuilding.name;
    }
  } else {
    formData.value.buildingName = '';
  }
});

const captchaText = ref('');
const generateCaptcha = () => {
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let captcha = "";
  for (let i = 0; i < 6; i++) {
    captcha += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  captchaText.value = captcha;
};

generateCaptcha();

const rules = ref({
  buildingId: [
    {required: true, message: '请选择教学楼或学院楼', trigger: 'change'}
  ],
  roomNumber: [
    {required: true, message: '房间号不能为空', trigger: 'blur'}
  ],
  contentTitle: [
    {required: true, message: '内容标题不能为空', trigger: 'blur'}
  ],
  contentDescription: [
    {required: true, message: '内容描述不能为空', trigger: 'blur'}
  ],
  contentImage: [
    {required: true, message: '请至少上传一张图片', trigger: 'change'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== captchaText.value) {
          callback(new Error('验证码输入错误'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

const handleUploadSuccess = (response, uploadFile) => {
  console.log('Upload Success:', response);
  formData.value.contentImage.push(response.data);
};

const handleUploadRemove = (file, fileList) => {
  formData.value.contentImage = fileList.map((file) => file.url);
};

const handleUploadExceed = () => {
  ElMessage.warning('最多只能上传6张图片');
};

const submitForm = () => {
  const teachingBuildingForm = ref(null);
  teachingBuildingForm.value.validate((valid) => {
    if (valid) {
      const formDataToSend = {
        ...formData.value,
        contentImage: JSON.stringify(formData.value.contentImage) // 转换为 JSON 字符串
      };
      axios.post('/teachingBuilding/add', formDataToSend)
          .then(response => {
            ElMessage.success('添加成功');
            router.push('/TeachingBuildingSelect');
          })
          .catch(error => {
            ElMessage.error('添加失败');
          });
    } else {
      ElMessage.error('表单信息填写不完整或有误，请检查！');
    }
  });
};
</script>

<style scoped>
.form-container {
  margin: 20px 0; /* 调整外边距，使其向左对齐 */
  padding: 20px;
}

/* 添加标题样式 */
.header {
  background: none;
  padding-top: 5px;
  text-align: left;
  font-size: 20px;
  line-height: 30px;
  font-weight: bold;
}

/* 添加带下划线的文字样式 */
.form-description {
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
  color: #666;
  text-align: left;
  line-height: 25px; /* 设置行高 */
}

.responsive-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 强制设置 placeholder 字体为 Zpix */
.form-container ::placeholder {
  font-family: "Zpix", sans-serif !important;
}

/* 强制设置输入框内容的字体为 Zpix */
.form-container input {
  font-family: "Zpix", sans-serif !important;
}
</style>